﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using Portal.Systems.Model;
using Portal.Core;
using Portal.Web.Utility;
using Portal.Web.Model;

namespace Portal.Systems.Render
{
    public class PermissionRenderBll
    {
        static void CheckPermission(string SiteId)
        {
            try
            {
                string UserId = WebSessionUtility.GetCurrentLoginUser().UserId;
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, SystemPermission.StaticId, SystemPermission.funcManage, SystemPermission.funcManage, UserId, true);
            }
            catch (Exception ex)
            {
                string ReturnData = "<div class=CssAccessDenied>" + ex.Message.ToString() + " <span class=CssBack><a href=\"javascript:history.back(-1);\">Quay lại</a></span></div>\r\n";
                throw new Exception(ReturnData);
            }
        }

        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                CheckPermission(SiteId);
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string ButtonIconUrl = WebConfig.GetButtonIconRoot(OSiteParam);
                string ptc = (string)WebEnvironments.Request(SiteId, "ptc");
                string oid = (string)WebEnvironments.Request(SiteId, "id");
                string act = (string)WebEnvironments.Request(SiteId, "act");
                if (string.IsNullOrEmpty(act)) act = "";
                IPermission OPermissionTemplate = WebPermissionUtility.Find(SiteId, ptc);
                if (OPermissionTemplate == null) throw new Exception("Không tìm thấy dịch vụ phân quyền!");
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).DeleteNotExistsInObject(SiteId, ptc);

                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).InitPermisison(SiteId, OPermissionTemplate);
                string BackSessionId = (string)WebEnvironments.Request(SiteId, "BackSessionId");
                string backAspx = "PermissionMan.aspx";
                if (!string.IsNullOrEmpty(BackSessionId))
                {
                    BackSessionCls OBackSession = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateBackSessionModel(SiteId, BackSessionId);
                    if (OBackSession != null)
                    {
                        backAspx = OSiteParam.HttpRoot+"/"+ OBackSession.Url;
                    }
                }
                
                string Html =
                   " <script language=javascript>\r\n" +
                   "    function ClientAddForPermission()\r\n" +
                   "    {\r\n" +
                   "        SiteId='"+SiteId+"';\r\n"+
                   "        ptc = document.getElementById('txtptc').value;\r\n"+
                   "        id = document.getElementById('txtid').value;\r\n"+
                   "        AccountType= document.getElementById('txtAccountType').value;\r\n" +
                   "        backsessionid= document.getElementById('txtBackSessionId').value;\r\n" +
                   "        window.open('AddPermission.aspx?ptc='+ptc+'&id='+id+'&act='+AccountType+'&backsessionid='+backsessionid,'_self');\r\n" +
                   "    }\r\n" +

                   "    function ClientShowPermissionList(id)\r\n"+
                   "    {\r\n" +
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        ptc = document.getElementById('txtptc').value;\r\n" +
                   "        act= document.getElementById('txtAccountType').value;\r\n" +
                   "        AjaxOut = Portal.Systems.Render.PermissionRenderBll.ServerSideDrawFunction(SiteId,ptc,id,act).value;\r\n" +
                   "        document.getElementById('divListFunction').innerHTML=AjaxOut.HtmlContent;\r\n"+
                   "    }\r\n" +

                   "    function ClientDeletePermisisonRole(PermissionRoleId)\r\n"+
                   "    {\r\n"+
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        if(confirm('Bạn đã chắc chắn xóa chưa?')==false)return;\r\n"+
                   "        ptc = document.getElementById('txtptc').value;\r\n" +
                   "        act= document.getElementById('txtAccountType').value;\r\n" +
                   "        AjaxOut = Portal.Systems.Render.PermissionRenderBll.ServerSideDeletePermissionRole(SiteId,ptc,PermissionRoleId,'"+oid+"').value;\r\n" +
                   "        document.getElementById('divListPermission').innerHTML=AjaxOut.HtmlContent;\r\n" +
                   "        document.getElementById('divListFunction').innerHTML=AjaxOut.RetExtraParam1;\r\n" +
                   "    }\r\n"+
                   
                   "    function ProcessCheckDetail(PermissionRoleDetailId)\r\n"+
                   "    {\r\n"+
                   "        CheckedPermissionDetailIds = document.getElementById('txtPermissionDetailIds').value;\r\n" +
                   "        bChecked=document.getElementById('chk'+PermissionRoleDetailId).checked;\r\n" +
                   "        AjaxOut = Portal.Systems.Render.PermissionRenderBll.ServerSideProcessCheckDetail(SiteId,CheckedPermissionDetailIds,PermissionRoleDetailId,bChecked).value;\r\n" +
                   "        document.getElementById('txtPermissionDetailIds').value=AjaxOut.HtmlContent;\r\n"+
                   "    }\r\n"+

                   "    function ClientExecuteSetPermission(PermissionRoleId)\r\n" +
                   "    {\r\n"+
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        PermissionDetailIds = document.getElementById('txtPermissionDetailIds').value;\r\n" +
                   "        AjaxOut = Portal.Systems.Render.PermissionRenderBll.ServerSideSetPermissionDetail(SiteId,PermissionRoleId,PermissionDetailIds).value;\r\n" +
                   "        if(AjaxOut.Error)\r\n" +
                   "        {\r\n" +
                   "            alert(AjaxOut.InfoMessage);\r\n" +
                   "            return;\r\n" +
                   "        }\r\n" +
                   "        alert(AjaxOut.InfoMessage);\r\n" +
                   "    }\r\n"+
                   " </script>\r\n" +
                   " <input id=\"txtptc\" type=hidden value=\""+ptc+"\">\r\n"+
                   " <input id=\"txtid\" type=hidden value=\"" + oid + "\">\r\n" +
                   " <input id=\"txtAccountType\" type=hidden value=\"" + act + "\">\r\n" +
                   " <input id=\"txtBackSessionId\" type=hidden value=\"" + BackSessionId + "\">\r\n" +
                   
                   " <div id=divListForm>\r\n" +
                   " <div class=DatabaseFunction>\r\n" +
                   "        <ul>\r\n" +
                   "            <li onclick=\"javascript:ClientAddForPermission();\"><img class=image src=\""+ButtonIconUrl+"/Add.png\"><div>Phân quyền cho</div></li>\r\n" +
                   //"            <li onclick=\"javascript:ClientDeleteFolder();\"><img class=image src=\"Resources/Images/Delete.png\"><div>Xóa đối tượng</div></li>\r\n" +
                   "            <li onclick=\"javascript:window.open('"+backAspx+"','_self');\"><img class=image src=\""+ButtonIconUrl+"/back.png\"><div>Quay lại</div></li>\r\n" +
                   "        </ul>\r\n" +
                   "  </div>\r\n" +
                   "  <table>\r\n" +
                   "    <tr>\r\n" +
                   "        <td>\r\n" +
                   "            <div class=\"CssListPermission\" id=\"divListPermission\">\r\n" +
                                    ServerSideReadingListPermission(SiteId, ptc, oid).HtmlContent +
                   "            </div>\r\n" +
                   "        </td>\r\n" +
                   "        <td>\r\n"+
                   "            <div id=divListFunction><h3>Phân quyền truy cập</h3></div>\r\n"+
                   "        </td>\r\n"+
                   "    </tr>\r\n" +
                   "   </table>\r\n" +
                   "</div>\r\n";
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>"+ ex.Message.ToString()+"</div>\r\n";
            }
            
            return OAjaxOut;
        }


        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideProcessCheckDetail(
            string SiteId, 
            string CheckedPermissionDetailIds,
            string PermissionDetailId,
            bool bChecked)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                if (bChecked)
                {
                    CheckedPermissionDetailIds = CheckedPermissionDetailIds + PermissionDetailId + ";";
                }
                else
                {
                    CheckedPermissionDetailIds = CheckedPermissionDetailIds.Replace(PermissionDetailId + ";", "");
                }
                CheckedPermissionDetailIds = CheckedPermissionDetailIds.Trim();
                int iFound = CheckedPermissionDetailIds.IndexOf(";;");
                while (iFound != -1) 
                {
                    CheckedPermissionDetailIds = CheckedPermissionDetailIds.Replace(";;", ";");
                    iFound = CheckedPermissionDetailIds.IndexOf(";;");
                }
                CheckedPermissionDetailIds = CheckedPermissionDetailIds.Trim();
                if (CheckedPermissionDetailIds.Length > 0)
                {
                    if (CheckedPermissionDetailIds[0] == ';')
                    {
                        CheckedPermissionDetailIds = CheckedPermissionDetailIds.Substring(1);
                    }
                }
                OAjaxOut.HtmlContent = CheckedPermissionDetailIds;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>" + ex.Message.ToString() + "</div>\r\n";
            }

            return OAjaxOut;
        }

         [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideSetPermissionDetail(
             string SiteId, 
             string PermissionRoleId,
             string CheckedPermissionDetailIds)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string[] Items = CheckedPermissionDetailIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).SetPermissionDetail(SiteId, PermissionRoleId, Items);
                OAjaxOut.InfoMessage = "Phân quyền thành công";

            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>" + ex.Message.ToString() + "</div>\r\n";
            }

            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideDeletePermissionRole(
            string SiteId,
            string ptc,
            string PermissionRoleId,
            string oid)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).DeletePermissionRole(SiteId, PermissionRoleId);
                OAjaxOut.InfoMessage = "Gỡ bỏ phân quyền cho đối tượng thành công";
                OAjaxOut.HtmlContent = ServerSideReadingListPermission(SiteId, ptc, oid).HtmlContent;
                OAjaxOut.RetExtraParam1 = "<h3>Phân quyền truy cập</h3>\r\n";
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>" + ex.Message.ToString() + "</div>\r\n";
            }

            return OAjaxOut;
        }

        

        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideDrawFunction(
            string SiteId, 
            string ptc, 
            string PermissionRoleId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                

                string PermissionDetailIds="";
                PermissionRoleDetailCls[] PermissionRoleDetails = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingPermissionRoleDetail(SiteId, ptc, PermissionRoleId);
                for (int iIndex = 0; iIndex < PermissionRoleDetails.Length; iIndex++)
                {
                    if (PermissionRoleDetails[iIndex].Allow == 1)
                    {
                        PermissionDetailIds = PermissionDetailIds + PermissionRoleDetails[iIndex].PermissionRoleDetailId + ";";
                    }
                }
                
                PermissionRoleCls OPermissionRole = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreatePermissionRoleModel(SiteId, PermissionRoleId);
                string Html =
                    "<input type=hidden id=txtPermissionDetailIds value=\"" + PermissionDetailIds + "\">\r\n" +
                    "<h3>" + OPermissionRole.DisplayInfo + "<input type=button class=button style=\"float:right\" value=\"Thiết lập\" onclick=\"javascript:ClientExecuteSetPermission('" + PermissionRoleId + "');\"></h3>\r\n" +
                    "<div class=ulFunction>\r\n"+
                    "<ul>\r\n";
                for (int iIndex = 0; iIndex < PermissionRoleDetails.Length; iIndex++)
                {
                    Html += " <li><input onchange=\"javascript:ProcessCheckDetail('"+PermissionRoleDetails[iIndex].PermissionRoleDetailId+"');\" class=checkbox type=checkbox " + (PermissionRoleDetails[iIndex].Allow==1?"CHECKED":"") + " id=\"chk" + PermissionRoleDetails[iIndex].PermissionRoleDetailId + "\">" + PermissionRoleDetails[iIndex].FunctionName + "</li>\r\n";
                }
                Html += "</ul>\r\n" +
                        "</div>\r\n";
                OAjaxOut.HtmlContent = Html;
                return OAjaxOut;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>" + ex.Message.ToString() + "</div>\r\n";
            }
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideReadingListPermission(string SiteId,string ptc,string oid)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string ButtonUrl = WebConfig.GetButtonIconRoot(OSiteParam);
                PermissionRoleCls[] PermissionRoles = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingPermissionRoles(SiteId, ptc, oid);
                string Html =
                    "<h3>Danh sách đối tượng được phân quyền</h3>\r\n";
                if (PermissionRoles.Length == 0)
                {
                    Html += "  <div class=CssNoData>Chưa có đối tượng nào được phân quyền</div>\r\n";
                }
                else
                {
                    Html += "<div class=tabcontent>\r\n" +
                            "   <table>\r\n";
                    for (int iIndex = 0; iIndex < PermissionRoles.Length; iIndex++)
                    {
                        string Icon = "RoleIcon.png";
                        if (PermissionRoles[iIndex].Type.Equals("user"))
                        {
                            Icon = "UserIcon.png";
                        }
                        Html += " <tr>\r\n" +
                                "    <td class=tdicon><img src=\""+ButtonUrl+"/"+Icon+"\" class=imageicon></td>\r\n" +
                                "    <td><a href=\"javascript:ClientShowPermissionList('" + PermissionRoles[iIndex].PermissionRoleId + "');\">" + PermissionRoles[iIndex].DisplayInfo + "</a></td>\r\n" +
                                "    <td class=tdButton><input type=button class=button value=\"Xóa\" onclick=\"javascript:ClientDeletePermisisonRole('" + PermissionRoles[iIndex].PermissionRoleId + "');\"></td>\r\n" +
                                "    <td class=tdButton><input type=button class=button value=\"Phân quyền\" onclick=\"javascript:ClientShowPermissionList('" + PermissionRoles[iIndex].PermissionRoleId + "');\"></td>\r\n" +
                                " </tr>\r\n";
                    }
                    Html += "</table>\r\n" +
                            "</div>\r\n";
                }
                OAjaxOut.HtmlContent = Html;
                return OAjaxOut;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>"+ ex.Message.ToString()+"</div>\r\n";
            }
            
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod]
        public static AjaxOut DrawAddRolePermisison(
            string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string ButtonRootUrl = WebConfig.GetButtonIconRoot(OSiteParam);
                string IconRoot = WebConfig.GetIconRoot(OSiteParam);
                string ptc = (string)WebEnvironments.Request(SiteId, "ptc");
                string oid = (string)WebEnvironments.Request(SiteId, "id");
                string act = (string)WebEnvironments.Request(SiteId, "act");
                if (string.IsNullOrEmpty(act)) act = "";
                string BackSessionId = (string)WebEnvironments.Request(SiteId, "BackSessionId");
                if (string.IsNullOrEmpty(BackSessionId)) BackSessionId = "";
         


                string AllAppendClass = "";
                if (string.IsNullOrEmpty(act))
                {
                    AllAppendClass = " class=active";
                }
                AccountTypeCls[] AccountTypes = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingAccountType(SiteId, null);
                

                string Html =
                   " <script language=javascript>\r\n"+
                   "    function ProcessCheck(type,id)\r\n"+
                   "    {\r\n"+
                   "        SiteId='"+SiteId+"';\r\n"+
                   "        CheckedIds='';\r\n "+
                   "        if(type=='role')\r\n"+
                   "        {\r\n"+
                   "            CheckedIds = document.getElementById('txtCheckedRoleIds').value;\r\n"+
                   "        }\r\n"+
                   "        if(type=='user')\r\n"+
                   "        {\r\n"+
                   "            CheckedIds = document.getElementById('txtCheckedUserIds').value;\r\n"+
                   "        }\r\n"+
                   "        bChecked=document.getElementById('chk'+id).checked;\r\n"+
                   "        AjaxOut = Portal.Systems.Render.PermissionRenderBll.ServerSideProcessingCheck(SiteId,CheckedIds,id,bChecked).value;\r\n" +
                   "        if(type=='role')\r\n" +
                   "        {\r\n" +
                   "            document.getElementById('txtCheckedRoleIds').value=AjaxOut.HtmlContent;\r\n" +
                   "        }\r\n" +
                   "        if(type=='user')\r\n" +
                   "        {\r\n" +
                   "            document.getElementById('txtCheckedUserIds').value=AjaxOut.HtmlContent;\r\n" +
                   "        }\r\n" +
                   "    }\r\n"+

                   "    function ClientExecuteAdd(BackSessionId)\r\n" +
                   "    {\r\n"+
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        ptc=document.getElementById('txtptc').value;\r\n"+
                   "        id=document.getElementById('txtid').value;\r\n" +
                   "        act=document.getElementById('txtAccountType').value;\r\n" +
                   "        CheckedRoleIds=document.getElementById('txtCheckedRoleIds').value;\r\n" +
                   "        CheckedUserIds=document.getElementById('txtCheckedUserIds').value;\r\n" +
                   "        AjaxOut = Portal.Systems.Render.PermissionRenderBll.ServerSideAddRolePermission(SiteId,ptc,id,act,CheckedRoleIds,CheckedUserIds,BackSessionId).value;\r\n" +
                   "        if(AjaxOut.Error)\r\n"+
                   "        {\r\n"+
                   "            window.open(AjaxOut.InfoMessage);\r\n"+
                   "            return;\r\n"+
                   "        }\r\n"+
                   "        window.open(AjaxOut.RetUrl,'_self');\r\n"+
                   "    }\r\n"+

                   "    function NextPage(CurrentPageIndex)\r\n"+
                   "    {\r\n"+
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        Keyword=document.getElementById('txtKeyword').value;\r\n"+
                   "        ptc=document.getElementById('txtptc').value;\r\n"+
                   "        id=document.getElementById('txtid').value;\r\n" +
                   "        act=document.getElementById('txtAccountType').value;\r\n" +
                   "        AjaxOut = Portal.Systems.Render.PermissionRenderBll.ServerSideReading(SiteId,ptc,id,act,Keyword, CurrentPageIndex).value;\r\n" +
                   "        document.getElementById('divObject').innerHTML=AjaxOut.HtmlContent;\r\n"+
                   "    }\r\n"+

                   "    function ClientSearch()\r\n" +
                   "    {\r\n"+
                   "        SiteId='" + SiteId + "';\r\n" +
                   "        NextPage(0);\r\n"+
                   "    }\r\n"+

                   " </script>\r\n"+
                   " <input id=\"txtptc\" type=hidden value=\"" + ptc + "\">\r\n" +
                   " <input id=\"txtid\" type=hidden value=\"" + oid + "\">\r\n" +
                   " <input id=\"txtAccountType\" type=hidden value=\"" + act + "\">\r\n" +
                   //" <input id=\"txtBackSessionId\" type=hidden value=\"" + BackSessionId + "\">\r\n" +
                   " <input id=\"txtCheckedRoleIds\" type=hidden value=\"\">\r\n" +
                   " <input id=\"txtCheckedUserIds\" type=hidden value=\"\">\r\n" +
                   
                   " <div class=DatabaseFunction>\r\n" +
                   "        <ul>\r\n" +
                   "            <li onclick=\"javascript:ClientExecuteAdd('"+BackSessionId+"');\"><img class=image src=\""+ButtonRootUrl+"/Save.png\"><div>Thực hiện</div></li>\r\n" +
                   "            <li onclick=\"javascript:window.open('Permission.aspx?ptc=" + ptc + "&id=" + oid + "&act=" + act + "&BackSessionId=" + BackSessionId + "','_self');\"><img class=image src=\"" + ButtonRootUrl + "/back.png\"><div>Quay lại</div></li>\r\n" +
                   "        </ul>\r\n" +
                   "  </div>\r\n" +
                    "<h3>Chọn đối tượng để phân quyền</h3>\r\n" +
                    "<div class=CssFormPermission>\r\n"+
                    "<table>\r\n"+
                    "<tr>\r\n"+
                    "<td class=tdAccountType>\r\n"+
                    "<div class=CssFilterAccountType>\r\n"+
                    "<ul>\r\n"+
                    " <li " + AllAppendClass + " onclick=\"javascript:window.open('AddPermission.aspx?ptc="+ptc+"&id="+oid+"','_self');\">" +
                    "   <div><img class=imageicon src=\"" + IconRoot + "/AccountType/all.png\"></div>\r\n" +
                    "   <div>Toàn bộ</div>\r\n" +
                    "</li>\r\n";
                for (int iIndex = 0; iIndex < AccountTypes.Length; iIndex++)
                {
                    string AppendClass = "";
                    if (AccountTypes[iIndex].AccountType.Equals(act))
                    {
                        AppendClass = " class=active";
                    }
                    Html +=
                        " <li " + AppendClass + " onclick=\"javascript:window.open('AddPermission.aspx?ptc="+ptc+"&id="+oid+"&act="+AccountTypes[iIndex].AccountType+"','_self');\">" +
                        "   <div><img class=imageicon src=\"" + IconRoot + "/AccountType/" + AccountTypes[iIndex].AccountType + ".png\"></div>\r\n" +
                        "   <div>"+AccountTypes[iIndex].Description + "</div>\r\n"+
                        "</li>\r\n";
                }
                Html +=
                   "    </ul>\r\n" +
                   "    </div>\r\n" +
                   "</td>\r\n" +
                   "<td>\r\n"+
                   "    <div id=divObject>"+ServerSideReading(SiteId,ptc,oid,act,"",0).HtmlContent+"</div>\r\n"+
                   "</td>\r\n" +
                   "</tr>\r\n" +
                   "</table>\r\n";
                OAjaxOut.HtmlContent = Html;
                return OAjaxOut;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>"+ ex.Message.ToString()+"</div>\r\n";
            }
            
            return OAjaxOut;
        }


        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideReading(
            string SiteId,
            string ptc,
            string oid,
            string act,
            string Keyword,
            int CurrentPageIndex)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string ButtonRootUrl = WebConfig.GetButtonIconRoot(OSiteParam);
             
                RoleCls[] Roles = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingRoleForPermission(SiteId, ptc, oid, act, Keyword);
                UserCls[] Users = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingUserForPermission(SiteId, ptc, oid, act, Keyword);
                ArrayList ArrayListObjects = new ArrayList();
                for (int iIndex = 0; iIndex < Roles.Length; iIndex++)
                {
                    ArrayListObjects.Add(Roles[iIndex]);
                }
                for (int iIndex = 0; iIndex < Users.Length; iIndex++)
                {
                    ArrayListObjects.Add(Users[iIndex]);
                }

                string Html = "";
                if (ArrayListObjects.Count > 0)
                {
                    ReturnPaging OReturnPaging= WebPaging.GetPaging(ArrayListObjects.Count, CurrentPageIndex,20, 10, "NextPage");
                    Html +=
                        OReturnPaging.PagingText+
                        "<div class=CssDivFunction>Từ khóa lọc: <input type=textbox class=textbox id=txtKeyword value=\"" + Keyword + "\"><input type=button class=button value=\"Lọc\"  onclick=\"javascript:ClientSearch();\"></div>\r\n" +
                        "<div class=tabcontent>\r\n" +
                        "   <table>\r\n";

                    for (int iIndex = OReturnPaging.StartIndex; iIndex < OReturnPaging.EndIndex; iIndex++)
                    {
                        object o = (object)ArrayListObjects[iIndex];
                        if (o.GetType() == typeof(RoleCls))
                        {
                            RoleCls ORole = (RoleCls)o;
                            Html +=
                                " <tr>\r\n" +
                                "    <td class=tdicon><img src=\""+ButtonRootUrl+"/RoleIcon.png\" class=imageicon></td>\r\n" +
                                "    <td><input onchange=\"javascript:ProcessCheck('role','" + ORole.RoleId + "');\" class=CssCheckBox type=checkbox id=chk" + ORole.RoleId + ">" + ORole.RoleName + "</td>\r\n" +
                                " </tr>\r\n";
                        }
                        if (o.GetType() == typeof(UserCls))
                        {
                            UserCls OUser = (UserCls)o;
                            Html +=
                                " <tr>\r\n" +
                                "    <td class=tdicon><img src=\""+ButtonRootUrl+"/UserIcon.png\" class=imageicon></td>\r\n" +
                                "    <td><input onchange=\"javascript:ProcessCheck('user','" + OUser.UserId + "');\"  type=checkbox class=CssCheckBox id=chk" + OUser.UserId + ">" + OUser.FullName + " / " + OUser.LoginName + "</td>\r\n" +
                                " </tr>\r\n";
                        }
                    }
                    Html += "</table>\r\n" +
                          "</div>\r\n";
                }
                else
                {
                    Html = "<div class=CssNoData>Không có đối tượng nào</div>\r\n";
                }
                OAjaxOut.HtmlContent = Html;
            }
            catch (Exception ex)
            {
                OAjaxOut.HtmlContent = ex.Message.ToString();
                OAjaxOut.InfoMessage = ex.Message.ToString();
            }
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideProcessingCheck(
            string SiteId, 
            string CheckedIds,
            string id,
            bool   Checked)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                if (Checked)
                {
                    CheckedIds = CheckedIds + id+";";
                }
                else
                {
                    CheckedIds = CheckedIds.Replace(id + ";", "");
                }
                int iFound = CheckedIds.IndexOf(";;");
                while(iFound!=-1)
                {
                    CheckedIds = CheckedIds.Replace(";;", ";");
                    iFound = CheckedIds.IndexOf(";;");
                }
                CheckedIds = CheckedIds.Trim();
                if (CheckedIds.Length > 0)
                {
                    if (CheckedIds[0] == ';')
                    {
                        CheckedIds = CheckedIds.Substring(1);
                    }
                }
                OAjaxOut.HtmlContent = CheckedIds;
                return OAjaxOut;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>" + ex.Message.ToString() + "</div>\r\n";
            }

            return OAjaxOut;
        }


        [AjaxPro.AjaxMethod]
        public static AjaxOut ServerSideAddRolePermission(
            string SiteId,
            string ptc,
            string id,
            string act,
            string RoleIds,
            string UserIds,
            string BackSessionId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                string[] ItemRoles=RoleIds.Split(new char[]{';'},StringSplitOptions.RemoveEmptyEntries);
                string[] ItemUsers = UserIds.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).AddRolePermission(SiteId, ptc, id, ItemRoles, ItemUsers);
                OAjaxOut.RetUrl = "Permission.aspx?ptc=" + ptc + "&id=" + id + "&AccountType=" + act + "&BackSessionId=" + BackSessionId;
                return OAjaxOut;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage = ex.Message.ToString();
                OAjaxOut.HtmlContent = "<div class=CssAccessDenied>" + ex.Message.ToString() + "</div>\r\n";
            }

            return OAjaxOut;
        }
    }
}
